package com.authine.cloudpivot.ext.controller.position;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.AccountAuthorize;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.DocAPI;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.authine.cloudpivot.ext.service.CloudSqlService;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.authine.cloudpivot.ext.Utils.RoleAuth;

//岗配配置
@Slf4j
@RestController
@RequestMapping("/public/PositionConfigBillController")
public class PositionConfigBillController extends BaseController {
    @Autowired
    CloudSqlService sqlService;

    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }
    @Async
    @GetMapping("delPerToPos")
    public ResponseResult delPerToPos(String bizId) {
        DocAPI api = new DocAPI();
        String token = api.getToken();
        String positionnumber = "";
        String personname = "";
        String personnumber = "";
        String RolePosId = "";
        String deptname = "";
        String SeniAttr = "";
        String positionname = "";
        String deptnumber = "";


        Map<String, Object> objectMap = null;

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("PositionConfigBillVoid", bizId);

        List<Map<String, Object>> subSheet = (List<Map<String, Object>>) bizObject.getObject("SheetPositionConfigBillVoid");


        int n = subSheet.size();
        for (int i = 0; i < n; i++) {
            objectMap = subSheet.get(i);
//            	api.getCopyFile(token, "2541888,2541909,2541930,2541951,2541972,2541993,2542014,2542035,2542056,2542077,2542098,2542119,2542140,2542161,2542182,2542203,2542224,2542245,2542266,2542287,2542308", "2518144");
//               	api.getCopyFile(token, "2541888,2541909,2541930,2541951", "2518144");


//            	api.getCopyFile(token, "2551548", "2518144");

            positionnumber = (String) objectMap.get("posNumber");// 获取岗位代码
            positionname = (String) objectMap.get("posName");// 获取岗位名称
            deptnumber = (String) objectMap.get("baseOrgNumber");// 获取基层组织代码
            deptname = (String) objectMap.get("baseOrgName");// 获取基层组织名称
            //Boolean charge = (Boolean) subSheet.get(0).get("charge");// 获取负责人岗
            personnumber = (String) objectMap.get("personNumber");// 获取人员代码
            personname = (String) objectMap.get("personName");// 获取人员名称


            String Attr = positionnumber + " PUB " + personnumber;
            net.sf.json.JSONObject PersonFolderIdObj = api.getFileID(Attr);
            int FolderNum = Integer.parseInt(PersonFolderIdObj.getString("num"));
            if (FolderNum > 0) {
                net.sf.json.JSONArray PersonFolderIdArray = PersonFolderIdObj.getJSONArray("data");
                net.sf.json.JSONObject PersonFolderIdDataArray = PersonFolderIdArray.getJSONObject(0);
                String PersonFolederId = PersonFolderIdDataArray.getString("id");
                api.getRemove(token, PersonFolederId);
            }
        }


//		String positionname="";
//		String positionnumber="";
//		String personnumber="";
//		String personname="";
//		String deptname="";
//		String SeniAttr="";
//		 String RolePosId="";
//
//		String str="select b.fname_l2 as positionname,b.fnumber as positionnumber ,c.fnumber as personnumber,c.fname_l2 as personname,d.fsimplename as deptname from T_POS_POSITIONCONFIGBASE a inner join  T_Org_POSITION b ON a.fpositionid=b.fid inner join t_ryx_ryxx c on c.fid=a.fpersonid inner join t_org_admin d on a.forgid =d.fid where a.fstatus='启用'  ";
//		IRowSet rs= SQLExecutorFactory.getLocalInstance(ctx,str).executeSQL();
//		try {
//			while (rs.next())
//			{
//				positionname=rs.getString("positionname");
//				positionnumber=rs.getString("positionnumber");
//				personnumber=rs.getString("personnumber");
//				personname=rs.getString("personname");
//				deptname=rs.getString("deptname");
//			    SeniAttr=positionnumber+" PUB "+deptname;
//			    net.sf.json.JSONObject FolderIdObj=api.getFileID( SeniAttr);
//			    int num=Integer.parseInt(FolderIdObj.getString("num"));
//			    if(num==0){continue;}
//			    net.sf.json.JSONArray FolderIdArray = FolderIdObj.getJSONArray("data");
//			    net.sf.json.JSONObject FolderArray1 = FolderIdArray.getJSONObject(0);
//				  String FolederId = FolderArray1.getString("id");
//			    String Attr=positionnumber+" PUB "+personnumber;
//			    api.getAddFolder(token, FolederId,personnumber+" "+ personname, Attr);
//			    net.sf.json.JSONObject PersonFolderIdObj=api.getFileID( Attr);
//			    net.sf.json.JSONArray PersonFolderIdArray = PersonFolderIdObj.getJSONArray("data");
//
//			    net.sf.json.JSONObject PersonFolderIdDataArray = PersonFolderIdArray.getJSONObject(0);
//				  String PersonFolederId = PersonFolderIdDataArray.getString("id");
//
//				  net.sf.json.JSONObject UserListObj=api.getListUser(token);
//				  net.sf.json.JSONArray UserListDataArray = UserListObj.getJSONArray("data");
//				  for (int i=0;i<UserListDataArray.size();i++){
//					   net.sf.json.JSONObject UserListArray = UserListDataArray.getJSONObject(i);
//					   if(UserListArray.getString("name").equals(personnumber+" "+personname)){
//					   RolePosId = UserListArray.getString("id");}
//				  }
//			RoleAuthDispatch.getRoleAuthDispatch(token, RolePosId, PersonFolederId, positionnumber+" "+positionname, "A");
//
//			}
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}


        return getOkResponseResult("成功");
    }

    @Async
    @GetMapping("addPerToPos")
    public ResponseResult addPerToPos(String bizId) {

        // TODO Auto-generated method stub
        DocAPI api = new DocAPI();
        String token = api.getToken();
        RoleAuth RoleAuth = new RoleAuth();
        String positionnumber = "";
        String personname = "";
        String personnumber = "";
        String RolePosId = "";
        String RolePosIdP = "";
        String PersonIdP = "";
        String archivetypenumber = "";
        String archivetypeserial = "";
        String archivetypename = "";
        String strSql02 = "";
        String strSql03 = "";
        String funnumber = "";
        String fundutyname = "";
        String funMemoryCode = "";
        String deptname = "";
        String SeniAttr = "";
        String AttrP = "";
        String PersonId = "";
        String positionname = "";
        String deptnumber = "";
        String firstPos = "";


        Map<String, Object> objectMap = null;

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject("PositionConfigBill", bizId);

        List<Map<String, Object>> subSheet = (List<Map<String, Object>>) bizObject.getObject("SheetPositionConfigBill");


        int n = subSheet.size();
        for (int i = 0; i < n; i++) {
            objectMap = subSheet.get(i);
//            	api.getCopyFile(token, "2541888,2541909,2541930,2541951,2541972,2541993,2542014,2542035,2542056,2542077,2542098,2542119,2542140,2542161,2542182,2542203,2542224,2542245,2542266,2542287,2542308", "2518144");
//               	api.getCopyFile(token, "2541888,2541909,2541930,2541951", "2518144");


//            	api.getCopyFile(token, "2551548", "2518144");

            positionnumber = (String) objectMap.get("posNumber");// 获取岗位代码
            positionname = (String) objectMap.get("posName");// 获取岗位名称
            deptnumber = (String) objectMap.get("baseOrgNumber");// 获取基层组织代码
            deptname = (String) objectMap.get("baseOrgName");// 获取基层组织名称
            firstPos = (String) objectMap.get("firstPos");// 获取第一岗
            personnumber = (String) objectMap.get("personNumber");// 获取岗位代码
            personname = (String) objectMap.get("personName");// 获取岗位名称


            String RolePosAName = positionnumber + " " + positionname;
            net.sf.json.JSONObject RolePosAObj01 = api.getRole(RolePosAName);
            net.sf.json.JSONArray RolePosADataArray01 = RolePosAObj01.getJSONArray("data");
            net.sf.json.JSONObject RolePosADataObj01 = RolePosADataArray01.getJSONObject(0);
            String RolePosAId = RolePosADataObj01.getString("id");

//			    net.sf.json.JSONObject finduserObj01 = api.getfinduseridbyname(token, personnumber+" "+personname);
//				   net.sf.json.JSONObject finduserObj01 = api.getfinduseridbyname(token, "test");
//
//			    net.sf.json.JSONArray finduserDataArray01 = finduserObj01.getJSONArray("data");
//				net.sf.json.JSONObject finduserDataObj01 = finduserDataArray01.getJSONObject(0);
//				PersonId = finduserDataObj01.getString("id");

            net.sf.json.JSONObject PUserListObj = api.getListUser(token);
            net.sf.json.JSONArray PUserListDataArray = PUserListObj.getJSONArray("data");
            for (int Pi = 0; Pi < PUserListDataArray.size(); Pi++) {
                net.sf.json.JSONObject PUserListArray = PUserListDataArray.getJSONObject(Pi);
                if (PUserListArray.getString("name").equals(personnumber + " " + personname)) {
                    PersonId = PUserListArray.getString("id");
                }
            }


////            //在监控后台将人员加到岗位
////            //获取监控后台token
//            String temp = "";
//            String RolePerson = "";
//            AccountAuthorize obj = new AccountAuthorize();
//            String FirstAuthorize = obj.testFirstAuthorize("system", "222.187.39.42:5443", "WINPC_V1");
//            log.info("FirstAuthorize:{}", FirstAuthorize);
//            JSONObject FirstAuthorizeObj = JSONObject.fromObject(FirstAuthorize);
//            log.info("FirstAuthorizeObj:{}", FirstAuthorizeObj.toString());
//            String realm = FirstAuthorizeObj.getString("realm");
//            String randomKey = FirstAuthorizeObj.getString("randomKey");
//            String encryptType = FirstAuthorizeObj.getString("encryptType");
//            String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlrrLOJnJE6MfIk82R2EbmBHv9cq6RaWKehuN5y8WiRfxDhwG2wE4ZFjjs831GcrZz8SZKcW/OcWlTs88JqleSbyDSAw+hxLSyCN9cKVO0rP7APYjS5XAus/77ftA4EO+2SKm+AKksx+ajm4vH2MfbXJOE2c9Ypd9nKYhONVH/pxauCtQmntt4gwX0+TnrAhPcQ2cUHkcLdAWYDFUUsabJFQr4JMuZ0C9L2N/lhj9koc2OLYNdiXUfxb0dXLrMhnO4Dbi/slW1PgQAolMXm4o161zFHI3KptlqkBrKfUiaZqcAyYOi3cNV8BrhtM2zRJ5qbyUhn0zmEzmkZZJvk+b4wIDAQAB";
//            String password = "ht123456";
//            String username = "system";
//            String Vediotoken = " ";
//            temp = md5(password);
//            temp = md5(username + temp);
//            temp = md5(temp);
//            temp = md5(username + ":" + realm + ":" + temp);
//            String signature = md5(temp + ":" + randomKey);
//            String SecondAuthorize = obj.testSecondAuthorize("C8:D9:D2:16:AF:F6", signature, username, randomKey, publicKey, encryptType, "192.168.11.43", "WINPC_V1", "0");
//            JSONObject SecondAuthorizeObj = JSONObject.fromObject(SecondAuthorize);
//            Vediotoken = SecondAuthorizeObj.getString("token");
////					      continue;
//            String RolePersonC = "";
//            String sqlRolePerson = "select b.FName_L2,c.FNumber FNumber,c.FName_L2  from   T_ORG_PositionMember  a  join  T_BD_Person  b  on  a.FPersonID=b.FID join   T_ORG_Position  c  on   a.FPositionID=c.FID where b.fnumber='" + personnumber + "'  	and  RIGHT(	c.FNumber,3) IN ('001','006')		";
//            List<Map<String, Object>> rsRolePerson = sqlService.getList(CloudSqlService.htEas, sqlRolePerson);
//            try {
//
//                for (Map<String, Object> m : rsRolePerson) {
//
//                    String fnumber = (String) m.get("FNUMBER");
//
//                    if (fnumber != null) {
//                        RolePerson = RolePerson + "," + fnumber;
//                        RolePersonC = RolePersonC + "," + fnumber + "C";
//                    }
//                }
//
//
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//
//            if (RolePerson.length() > 0) {
//                RolePerson = RolePerson.substring(1, RolePerson.length());
//                RolePersonC = RolePersonC.substring(1, RolePersonC.length());
//                obj.UpdateUser(Vediotoken, personnumber, RolePerson);
//                String personnumberC = personnumber + "C";
//                obj.UpdateUser(Vediotoken, personnumberC, RolePersonC);
//            }

            //在云盘后台将人员加到岗位


            api.getAddusertorole(token, PersonId, RolePosAId);


            //增加报批档案文件夹
            SeniAttr = positionnumber + " PUB " + deptname;
            net.sf.json.JSONObject FolderIdObj = api.getFileID(SeniAttr);
            net.sf.json.JSONArray FolderIdArray = FolderIdObj.getJSONArray("data");
            net.sf.json.JSONObject FolderArray1 = FolderIdArray.getJSONObject(0);
            String FolederId = FolderArray1.getString("id");
            String Attr = positionnumber + " PUB " + personnumber;
            net.sf.json.JSONObject NewFolderIdObj = api.getFileID(Attr);
            String num = NewFolderIdObj.getString("num");
            int num01 = Integer.parseInt(NewFolderIdObj.getString("num"));
            api.getAddFolder(FolederId, personnumber + " " + personname, Attr);
            net.sf.json.JSONObject PersonFolderIdObj = api.getFileID(Attr);
            net.sf.json.JSONArray PersonFolderIdArray = PersonFolderIdObj.getJSONArray("data");
            net.sf.json.JSONObject PersonFolderIdDataArray = PersonFolderIdArray.getJSONObject(num01 - 1);
            String PersonFolederId = PersonFolderIdDataArray.getString("id");
            //授予对应岗及其领导下载权限
            RoleAuth.RoleAuthDis(positionnumber, positionname, PersonFolederId);
            net.sf.json.JSONObject UserListObj = api.getListUser(token);
            net.sf.json.JSONArray UserListDataArray = UserListObj.getJSONArray("data");
            int gsfd = UserListDataArray.size();
            for (int j = 0; j < UserListDataArray.size(); j++) {
                net.sf.json.JSONObject UserListArray = UserListDataArray.getJSONObject(j);
                if (UserListArray.getString("name").equals(personnumber + " " + personname)) {
                    RolePosId = UserListArray.getString("id");

                    //授予对应人员上传、下载、修改权限
                    api.getRoleAuth(personnumber + " " + personname, RolePosId, "A", PersonFolederId);
                }
            }


            //增加个人文件夹
            SeniAttr = "PERSONAL-" + positionnumber.substring(0, positionnumber.indexOf(".")) + " " + positionnumber;
            net.sf.json.JSONObject FolderIdObjP = api.getFileID(SeniAttr);
            int Pnum = Integer.parseInt(FolderIdObjP.getString("num"));
            if (Pnum == 0) {
                continue;
            }
            net.sf.json.JSONArray FolderIdArrayP = FolderIdObjP.getJSONArray("data");
            net.sf.json.JSONObject FolderArray1P = FolderIdArrayP.getJSONObject(0);
            String FolederIdP = FolderArray1P.getString("id");
            AttrP = positionnumber + " PERSONAL " + personnumber;
            api.getAddFolder(FolederIdP, personnumber + " " + personname, AttrP);
            net.sf.json.JSONObject PersonFolderIdObjP = api.getFileID(AttrP);
            net.sf.json.JSONArray PersonFolderIdArrayP = PersonFolderIdObjP.getJSONArray("data");
            net.sf.json.JSONObject PersonFolderIdDataArrayP = PersonFolderIdArrayP.getJSONObject(0);
            String PersonFolederIdP = PersonFolderIdDataArrayP.getString("id");
            //授予对应岗及其领导下载权限
            RoleAuth.RoleAuthDis(positionnumber, positionname, PersonFolederIdP);
            net.sf.json.JSONObject UserListObjPP = api.getListUser(token);
            net.sf.json.JSONArray UserListDataArrayPP = UserListObjPP.getJSONArray("data");
            for (int P = 0; P < UserListDataArrayPP.size(); P++) {
                net.sf.json.JSONObject UserListArrayP = UserListDataArrayPP.getJSONObject(P);
                if (UserListArrayP.getString("name").equals(personnumber + " " + personname)) {
                    PersonIdP = UserListArrayP.getString("id");
                }
            }
            //授予对应人员所有权限
            api.getRoleAuth(personnumber + " " + personname, PersonIdP, "A", PersonFolederIdP);
            //如果人员文件夹下为空，则加相应档案和职能文件夹
            net.sf.json.JSONObject SubmitPubFolderIDObj = api.getList(PersonFolederIdP);
            boolean SubmitPubFolderIsEmpty = SubmitPubFolderIDObj.getJSONArray("data").isEmpty();
            if (SubmitPubFolderIsEmpty = true) {
                String hgj = positionnumber.substring(0, positionnumber.indexOf("."));
                if (hgj.equals("02") || hgj.equals("0301")) {
                    //个人文件-02 HT 浩通科技-总经办-夏军
                    api.getCopyFile(token, "2551547,2551548,2551549,2551550,2551551,2551552,2551553,2551554,2551555,2551556,2551557,2551558,2551559,2551560,2551561,2551562,2551563,2551564,2551565,2551566,2551567", PersonFolederIdP);
                }
                if (hgj.equals("06")) {
                    //个人文件-0201-总经办-夏军
                    api.getCopyFile(token, "3553943,3553944,3553945,3553946,3553947,3553948,3553949,3553950,3553951,3553952,3553953,3553954,3553955,3553956,3553957,3553958,3553959,3553960,3553961,3553962,3553963", PersonFolederIdP);
                }
                if (hgj.equals("05")) {
                    //个人文件-0201-总经办-夏军
                    api.getCopyFile(token, "4021508,4021509,4021510,4021511,4021512,4021513,4021514,4021515,4021516,4021517,4021518,4021519,40215120,40215121,40215122,40215123,40215124,40215125,40215126,40215127,40215128", PersonFolederIdP);
                }
            }
            //如果是第一岗位，则增加HR文件夹
//             boolean isMainPosition=dfentry.isMainPosition();
//             if(isMainPosition){
//              String HRParentFolderAttr="HR-"+OrgCodeInfo.getNumber().substring(0, OrgCodeInfo.getNumber().indexOf("."))+" "+positionnumber;
//              net.sf.json.JSONObject HRParentFolderObj=api.getFileID( HRParentFolderAttr);
//			  net.sf.json.JSONArray HRParentFolderArray = HRParentFolderObj.getJSONArray("data");
//			  net.sf.json.JSONObject HRParentFolderArray1 = HRParentFolderArray.getJSONObject(0);
//			  String HRParentFolderId = HRParentFolderArray1.getString("id");
//			  String HRFolderAttr=positionnumber+" HR "+personnumber;
//			  net.sf.json.JSONObject HRFolderIdObj=api.getFileID( HRFolderAttr);
//			  String HRNum=HRFolderIdObj.getString("num");
//			  if(HRNum.equals("0"))
//			  {
//	              api.getAddFolder( HRParentFolderId,personnumber+" "+ personname, HRFolderAttr);
//	           }
//				else
//				{
//				    	net.sf.json.JSONArray HRFolderIdArray = HRFolderIdObj.getJSONArray("data");
//					    net.sf.json.JSONObject HRFolderArray1 = HRFolderIdArray.getJSONObject(0);
//					    String HRFolederId = HRFolderArray1.getString("id");
//				    	api.getRename(token, HRFolederId, personnumber+" "+ personname);
//				 }
//             }


//             如果是第一岗位，则将人事档案文件夹转移到第一岗位下
            //Boolean isMainPosition = (Boolean) subSheet.get(0).get("charge");// 获取负责人岗

            if ("√".equals(firstPos)) {
                String HRParentFolderAttr = "HR-" + deptnumber.substring(0, deptnumber.indexOf(".")) + " " + positionnumber;
                net.sf.json.JSONObject HRParentFolderObj = api.getFileID(HRParentFolderAttr);
                net.sf.json.JSONArray HRParentFolderArray = HRParentFolderObj.getJSONArray("data");
                net.sf.json.JSONObject HRParentFolderArray1 = HRParentFolderArray.getJSONObject(0);
                String HRParentFolderId = HRParentFolderArray1.getString("id");
                String HRFolderAttr = "HR " + personnumber;
                net.sf.json.JSONObject HRFolderIdObj = api.getFileID(HRFolderAttr);
                String HRNum = HRFolderIdObj.getString("num");
                if (HRNum.equals("0")) {
                    api.getAddFolder(HRParentFolderId, personnumber + " " + personname, HRFolderAttr);
                } else {
                    net.sf.json.JSONArray HRFolderIdArray = HRFolderIdObj.getJSONArray("data");
                    net.sf.json.JSONObject HRFolderArray1 = HRFolderIdArray.getJSONObject(0);
                    String HRFolederId = HRFolderArray1.getString("id");
                    api.getRename(token, HRFolederId, personnumber + " " + personname);


//					    	String ExistFolderAttribute ="HR-" +OrgCodeInfo.getNumber()+ ' '+ positionnumber;
//							net.sf.json.JSONObject ExistFolderObj = api.getFileID(HRParentFolderAttr);//
//							net.sf.json.JSONArray ExistFolderDataArray = ExistFolderObj.getJSONArray("data");
//							net.sf.json.JSONObject ExistFolderObj0 = ExistFolderDataArray.getJSONObject(0);
//							String ExitFolderId = ExistFolderObj0.getString("id");
                    net.sf.json.JSONObject ExitFolderFullPath = api.getFullPath(HRParentFolderId);
                    String SubItemFolderDestFullpath = ExitFolderFullPath.getString("fullPath");


                    net.sf.json.JSONObject SubItemFileIdObj = api.getFileID(HRFolderAttr);
                    net.sf.json.JSONArray SubItemFileIdDataArray = SubItemFileIdObj.getJSONArray("data");
                    net.sf.json.JSONObject SubItemFileIdDataObj = SubItemFileIdDataArray.getJSONObject(0);
                    String SubItemFileId = SubItemFileIdDataObj.getString("id");
                    api.getMove(SubItemFileId, SubItemFolderDestFullpath);
                }
            }
//


            //给第一岗位员工授（文档工具）文件夹权限 本人上传下载删除权限，领导下载权限。
            String str = "select b.fname_l2 as positionname,b.fnumber as positionnumber ,c.fnumber as personnumber,c.fname_l2 as personname,d.fsimplename as deptname from [HG_LINK].[hg].[dbo].T_pos_positionconfigbase a INNER JOIN [HG_LINK].[hg].[dbo].T_Org_POSITION b ON a.fpositionid = b.fid INNER JOIN [HG_LINK].[hg].[dbo].t_BD_PERSON c ON c.fid = a.fempid INNER JOIN [HG_LINK].[hg].[dbo].t_org_admin d ON b.fadminorgunitid = d.fid WHERE a.fisfirst = '1' AND A.FSTATUS='启用' AND c.fnumber='" + personnumber + "'";
            String name = "";
            List<Map<String, Object>> rs = sqlService.getList(CloudSqlService.htEas, str);
            try {

                for (Map<String, Object> m : rs) {

                    positionname = (String) m.get("positionname");
                    positionnumber = (String) m.get("positionnumber");
                    personnumber = (String) m.get("personnumber");
                    personname = (String) m.get("personname");
                    deptname = (String) m.get("deptname");

                    if (positionname != null) {
                        name = positionnumber.substring(positionnumber.lastIndexOf(".") + 1, positionnumber.length()) + " " + positionname + " " + personname;
                        String remarks = positionnumber + " TOOL " + positionnumber.substring(0, positionnumber.lastIndexOf("."));
                        net.sf.json.JSONObject TNewFolderIdObj = api.getFileID(remarks);
                        String Tnum = TNewFolderIdObj.getString("num");
                        if (Tnum.equals("0")) {
                            String aaa = positionnumber.substring(0, positionnumber.lastIndexOf(".")) + " TOOL " + deptname;
                            net.sf.json.JSONObject SFolderIdObj = api.getFileID(aaa);
                            net.sf.json.JSONArray SFolderIdArray = SFolderIdObj.getJSONArray("data");
                            net.sf.json.JSONObject SFolderArray1 = SFolderIdArray.getJSONObject(0);
                            String SFolederId = SFolderArray1.getString("id");
                            api.getAddFolder(SFolederId, name, positionnumber + " TOOL " + positionnumber.substring(0, positionnumber.lastIndexOf(".")));
                        }

                        if (Tnum.equals("1")) {

                            net.sf.json.JSONArray NewFolderIdArray = TNewFolderIdObj.getJSONArray("data");
                            net.sf.json.JSONObject NewFolderArray1 = NewFolderIdArray.getJSONObject(0);
                            String NewFolederId = NewFolderArray1.getString("id");
                            api.getRename(token, NewFolederId, name);
                        }


                        Attr = positionnumber + " TOOL " + positionnumber.substring(0, positionnumber.lastIndexOf("."));//02.01.001 TOOL 02.01
                        net.sf.json.JSONObject TOOLPersonFolderIdObj = api.getFileID(Attr);
                        int TOOLnum01 = Integer.parseInt(TOOLPersonFolderIdObj.getString("num"));
                        if (TOOLnum01 == 0) {
                            continue;
                        }
                        net.sf.json.JSONArray TOOLPersonFolderIdArray = TOOLPersonFolderIdObj.getJSONArray("data");
                        net.sf.json.JSONObject TOOLPersonFolderIdDataArray = TOOLPersonFolderIdArray.getJSONObject(0);
                        String TOOLPersonFolederId = TOOLPersonFolderIdDataArray.getString("id");
                        net.sf.json.JSONObject TOOLUserListObj = api.getListUser(token);
                        net.sf.json.JSONArray TOOLUserListDataArray = TOOLUserListObj.getJSONArray("data");
                        for (int TOOLi = 0; TOOLi < TOOLUserListDataArray.size(); TOOLi++) {
                            net.sf.json.JSONObject UserListArray = TOOLUserListDataArray.getJSONObject(TOOLi);
                            if (UserListArray.getString("name").equals(personnumber + " " + positionname)) {
                                RolePosId = UserListArray.getString("id");
                            }
                            if (UserListArray.getString("name").equals(personnumber + " " + personname)) {
                                PersonId = UserListArray.getString("id");
                            }
                        }
                        //文档工具-02 HT 浩通科技-总经办-夏军
                        api.getCopyFile(token, "3554947,3554948,3555002,3554950,3554951,3554952,3554953,3554954,3554955,3554956,3554957,3554958,3554959,3554960,3554961,3554962,3554963,3554964,3554965,3554966,3554967,3554968,3554969,3554970", TOOLPersonFolederId);

// 					授某个文件给某个岗位，上级直到董事长授下载权
                        RoleAuth.RoleAuthDis(positionnumber, positionnumber + " " + positionname, TOOLPersonFolederId);
// 					 授权第一责任人所有权限
                        api.getRoleAuth(personnumber + " " + personname, PersonIdP, "A", TOOLPersonFolederId);

                    }
                }


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


//		String positionname="";
//		String positionnumber="";
//		String personnumber="";
//		String personname="";
//		String deptname="";
//		String SeniAttr="";
//		 String RolePosId="";
//
//		String str="select b.fname_l2 as positionname,b.fnumber as positionnumber ,c.fnumber as personnumber,c.fname_l2 as personname,d.fsimplename as deptname from T_POS_POSITIONCONFIGBASE a inner join  T_Org_POSITION b ON a.fpositionid=b.fid inner join t_ryx_ryxx c on c.fid=a.fpersonid inner join t_org_admin d on a.forgid =d.fid where a.fstatus='启用'  ";
//		IRowSet rs= SQLExecutorFactory.getLocalInstance(ctx,str).executeSQL();
//		try {
//			while (rs.next())
//			{
//				positionname=rs.getString("positionname");
//				positionnumber=rs.getString("positionnumber");
//				personnumber=rs.getString("personnumber");
//				personname=rs.getString("personname");
//				deptname=rs.getString("deptname");
//			    SeniAttr=positionnumber+" PUB "+deptname;
//			    net.sf.json.JSONObject FolderIdObj=api.getFileID( SeniAttr);
//			    int num=Integer.parseInt(FolderIdObj.getString("num"));
//			    if(num==0){continue;}
//			    net.sf.json.JSONArray FolderIdArray = FolderIdObj.getJSONArray("data");
//			    net.sf.json.JSONObject FolderArray1 = FolderIdArray.getJSONObject(0);
//				  String FolederId = FolderArray1.getString("id");
//			    String Attr=positionnumber+" PUB "+personnumber;
//			    api.getAddFolder( FolederId,personnumber+" "+ personname, Attr);
//			    net.sf.json.JSONObject PersonFolderIdObj=api.getFileID( Attr);
//			    net.sf.json.JSONArray PersonFolderIdArray = PersonFolderIdObj.getJSONArray("data");
//
//			    net.sf.json.JSONObject PersonFolderIdDataArray = PersonFolderIdArray.getJSONObject(0);
//				  String PersonFolederId = PersonFolderIdDataArray.getString("id");
//
//				  net.sf.json.JSONObject UserListObj=api.getListUser(token);
//				  net.sf.json.JSONArray UserListDataArray = UserListObj.getJSONArray("data");
//				  for (int i=0;i<UserListDataArray.size();i++){
//					   net.sf.json.JSONObject UserListArray = UserListDataArray.getJSONObject(i);
//					   if(UserListArray.getString("name").equals(personnumber+" "+personname)){
//					   RolePosId = UserListArray.getString("id");}
//				  }
//			RoleAuthDispatch.getRoleAuthDispatch( RolePosId, PersonFolederId, positionnumber+" "+positionname, "A");
//
//			}
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}


        return getOkResponseResult("成功");
    }

    @Async
    @GetMapping("/finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.PositionConfigBillAdd, bizId);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("SheetPositionConfigBill");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {

            try {
                //获取数据
                Map<String, Object> data = dataInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.PositionConfigBillBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-岗位配置信息基础作成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                String companyNumber = (String) map.get("companyCode");
                String posNumber = (String) map.get("posNumber");

                log.info("基础表-岗位配置信息基础操作失败 companyNumber={},posNumber={}", companyNumber, posNumber);
                log.info(e.getMessage(), e);
            }

        }
    }
    @Async
    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.PositionConfigBillVoid, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("SheetPositionConfigBillVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {


            try {
                //获取数据
                Map<String, Object> data = dataInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.PositionConfigBillBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-人员信息基础作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
                String companyNumber = (String) map.get("companyNumber");
                String personNumber = (String) map.get("personNumber");
                log.info("基础表-人员信息基础作废操作失败 personNumber={},companyNumber={}", personNumber, companyNumber);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     * 调用存储过程
     * <p>
     * -------岗位配置信息记录   配置信息
     * exec    SyncPositionConfig
     *
     * @PosNumber nvarchar(100),            ----岗位代码
     * @isfirst int,                ----第一责任 0  否   1  是
     * @ismain int,                ----是否主岗 0  否   1  是
     * @EmpCode nvarchar(50),            ----人员代码
     * @Ratifie nvarchar(10),            ----核定编制
     * @Allocate nvarchar(10),            ----分配编制
     * @Auditor nvarchar(50)            ----审批人 02.0100 李*
     */
    private void callProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.PositionConfigBillBase);
        StringBuilder sql = new StringBuilder("SELECT posNumber,firstRes,firstPos,personNumber,approvedNumber,dispatch,auditer,auditDate from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        //调用存储过程

        String posNumber = MapUtils.getString(map, "posNumber", "");
        String firstResTemp = MapUtils.getString(map, "firstRes", "");
        Integer firstRes = "√".equals(firstResTemp) ? 1 : 0;
        String firstPosTemp = MapUtils.getString(map, "firstPos", "");
        Integer firstPos = "√".equals(firstPosTemp) ? 1 : 0;
        String personNumber = MapUtils.getString(map, "personNumber", "");
        String approvedNumber = MapUtils.getString(map, "approvedNumber", "");

        String dispatch = MapUtils.getString(map, "dispatch", "");
        String auditer = MapUtils.getString(map, "auditer", "");

        Assert.isFalse(StringUtils.isEmpty(posNumber), "{}不能为空", "baseOrgId");
//        Assert.isFalse(firstDept==null ,"{}不能为空","firstDept");
        //Assert.isFalse(StringUtils.isEmpty(firstRes),"{}不能为空","baseOrgId");
        //Assert.isFalse(StringUtils.isEmpty(firstPos),"{}不能为空","posNumber");
        Assert.isFalse(StringUtils.isEmpty(personNumber), "{}不能为空", "posName");
        Assert.isFalse(StringUtils.isEmpty(approvedNumber), "{}不能为空", "effectiveDate");
        // Assert.isFalse(StringUtils.isEmpty(posDisableStatus),"{}不能为空","posDisableStatus");
        Assert.isFalse(StringUtils.isEmpty(dispatch), "{}不能为空", "expiryDate");
        Assert.isFalse(StringUtils.isEmpty(auditer), "{}不能为空", "auditer");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncPositionConfig     '%s','%s','%s','%s','%s','%s','%s'  ",
                posNumber, firstRes, firstPos, personNumber, approvedNumber, dispatch, auditer);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");


    }

    /**
     * 调用作废存储过程
     * ------岗位配置信息记录   配置信息作废
     * exec     PositionConfigVoid
     *
     * @param bizId
     * @PosNumber nvarchar(50),            ----岗位代码
     * @EmpCode nvarchar(50)            ----人员代码
     */
    private void callProcessToVoid(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.PositionConfigBillBase);
        StringBuilder sql = new StringBuilder("SELECT posNumber,personNumber from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程

        String personNumber = MapUtils.getString(map, "personNumber", "");
        String posNumber = MapUtils.getString(map, "posNumber", "");


        Assert.isFalse(StringUtils.isEmpty(posNumber), "{}不能为空", "posNumber");
        Assert.isFalse(StringUtils.isEmpty(personNumber), "{}不能为空", "personNumber");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].PositionConfigVoid '%s' ,'%s'",
                posNumber, personNumber);

        log.info("\n==========准备调用作废存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map<String, Object> data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.PositionConfigBillBase);

        String posNumber = (String) data.get("posNumber");
        String personNumber = (String) data.get("personNumber");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where posNumber ='").append(posNumber)
                .append("' and personNumber='").append(personNumber)
                .append("';");


        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity18";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */

    private Map<String, Object> dataInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();
        //关联公司
        data.put("companyId", map.get("companyId"));
        //公司代码
        data.put("companyCode", map.get("companyCode"));
        //公司名称
        data.put("companyName", map.get("companyName"));

        //关联基层组织代码
        data.put("bseOrgId", map.get("baseOrgId"));
        //基层组织代码
        data.put("bseOrgNumber", map.get("baseOrgNumber"));
        //基层组织名称
        data.put("bseOrgName", map.get("baseOrgName"));

        //岗代码
        data.put("RelevancePos", map.get("relevancePos"));
        //岗代码
        data.put("posNumber", map.get("posNumber"));
        //岗名称
        data.put("posName", map.get("posName"));


        //核定编制
        data.put("approvedNumber", map.get("approvedNumber"));
        //人员代码
        data.put("RelevancePerson", map.get("RelevancePerson"));
        //人员代码
        data.put("personNumber", map.get("personNumber"));
        //人员名称
        data.put("personName", map.get("personName"));


        //分配编制
        data.put("dispatch", map.get("dispatch"));
        //第一岗
        data.put("firstPos", map.get("firstPos"));
        //第一责任
        data.put("firstRes", map.get("firstRes"));

        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);

        return data;
    }


}
